package com.maixy.studyonlineapi.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.maixy.studyonlineapi.bean.Page;
import com.maixy.studyonlineapi.entity.ActivityContent;
import com.maixy.studyonlineapi.entity.ActivityContentBrowseRecord;
import com.maixy.studyonlineapi.entity.Media;
import com.maixy.studyonlineapi.entity.UserAbility;
import com.maixy.studyonlineapi.enums.MediaTypeEnum;
import com.maixy.studyonlineapi.exceptions.TipException;
import com.maixy.studyonlineapi.mapper.ActivityContentMapper;
import com.maixy.studyonlineapi.result.PageData;
import com.maixy.studyonlineapi.utils.DataTypeUtil;
import com.maixy.studyonlineapi.utils.OssUtil;
import com.maixy.studyonlineapi.view.ActivityContentView;
import com.maixy.studyonlineapi.view.MediaView;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * @ClassName ActivityContentService
 * @Description TODO
 * @Date 2020/11/29 17:24
 * @Author maixy
 */
@Service
public class ActivityContentService extends BaseMPlusService<ActivityContent, Long>{
    private final ActivityContentMapper activityContentMapper;

    @Resource
    private MediaService mediaService;
    @Resource
    private TeamService teamService;
    @Resource
    private UserAbilityService userAbilityService;
    @Resource
    private OssUtil ossUtil;
    @Resource
    private ActivityContentBrowseRecordService activityContentBrowseRecordService;

    protected ActivityContentService(ActivityContentMapper activityContentMapper) {
        super(ActivityContent.class, activityContentMapper);
        this.activityContentMapper = activityContentMapper;
    }

    /**
     * 获得课程内容列表
     * @param activityId 活动id
     * @param page 页面信息
     * @param activityContentSearch 关键字
     * @param hasStudent 是否是学生
     * @return PageData<com.maixy.studyonlineapi.view.ActivityContentView>
     */
    public PageData<ActivityContentView> activityContentList(Long activityId, Long userId, String activityContentSearch, Boolean hasStudent, Page page) {
        page.setHasMore(false);
        PageData<ActivityContentView> pageData = new PageData<>();
        pageData.setPage(page);
        pageData.setData(Collections.emptyList());
        int beginIndex = (page.getPage() - 1) * page.getSize();
        if (StringUtils.isNotBlank(activityContentSearch)) {
            activityContentSearch = "%".concat(activityContentSearch).concat("%");
        }
        List<ActivityContent> activityContentList;
        if (hasStudent) {
            UserAbility userAbility = userAbilityService.findUserAbilityBuUserIdAndActivityId(userId, activityId);
            if (null == userAbility || userAbility.getHasDelete()) {
                activityContentList = activityContentMapper.getMyActivityContentList(activityId, activityContentSearch,
                        0, 0, beginIndex, page.getSize() + 1);
            } else {
                activityContentList = activityContentMapper.getMyActivityContentList(activityId, activityContentSearch,
                        userAbility.getContentLevel(), userAbility.getContentType(), beginIndex, page.getSize() + 1);
            }
        } else {
            activityContentList = activityContentMapper.getMyActivityContentList(activityId, activityContentSearch,
                    0, 0, beginIndex, page.getSize() + 1);
        }
        if (CollectionUtils.isEmpty(activityContentList)) {
            return pageData;
        }
        if (activityContentList.size() > page.getSize()) {
            page.setHasMore(true);
            activityContentList.remove(activityContentList.size() - 1);
        }
        List<ActivityContentView> activityContentViewList = Lists.newArrayList();
        for (ActivityContent activityContent : activityContentList) {
            activityContentViewList.add(convert(activityContent, userId));
        }
        pageData.setData(activityContentViewList);
        return pageData;
    }

    /**
     * 课程内容视图
     * @param activityContent 课程内容实体
     * @param userId 当前用户id
     * @return com.maixy.studyonlineapi.view.ActivityContentView
     */
    public ActivityContentView convert(ActivityContent activityContent, Long userId) {
        ActivityContentView view = new ActivityContentView();
        Media media = mediaService.findById(activityContent.getMediaId());
        if (null == media || media.getHasDelete()) {
            throw new TipException("媒体文件不存在或已被删除");
        }
        view.setMediaView(mediaService.convert(media));
        view.setActivityContentId(DataTypeUtil.getStr(activityContent.getId()));
        view.setContentLevel(activityContent.getContentLevel());
        view.setContentType(activityContent.getContentType());
        view.setContentName(activityContent.getContentName());
        ActivityContentBrowseRecord record = activityContentBrowseRecordService.findBrowseRecord(userId, activityContent.getId());
        view.setHasBrowse(null != record && !record.getHasDelete());
        return view;
    }

    /**
     * 添加课程内容
     * @param teamId 团队di
     * @param userId 用户id
     * @param activityId 课程id
     * @param activityContentUrl 媒体文件Url
     * @param contentLevel 内容等级
     * @param contentType 课件类型
     * @param contentName 内容名称
     */
    public void saveActivityContent(Long teamId, Long userId, Long activityId, String activityContentUrl, Integer contentLevel, Integer contentType, String contentName) {
        if (!teamService.hasPower(teamId, userId)) {
            throw new TipException("没有权限");
        }
        if (ossUtil.exist(activityContentUrl)) {
            MediaView mediaView = new MediaView();
            if (MediaTypeEnum.VIDEO.getCode().equals(contentType)) {
                mediaView = mediaService.saveMedia(MediaTypeEnum.VIDEO.getCode(), activityContentUrl);
            } else if (MediaTypeEnum.PDF.getCode().equals(contentType)) {
                mediaView = mediaService.saveMedia(MediaTypeEnum.PDF.getCode(), activityContentUrl);
            } else {
                throw new TipException("暂不支持这种文件类型的课件");
            }
            ActivityContent activityContent = new ActivityContent();
            activityContent.setActivityId(activityId);
            activityContent.setMediaId(DataTypeUtil.getLong(mediaView.getMediaId()));
            activityContent.setContentLevel(contentLevel);
            activityContent.setContentType(contentType);
            activityContent.setContentName(contentName);
            activityContent.setCreateBy(userId);
            activityContent.setCreateTime(System.currentTimeMillis());
            activityContent.setHasDelete(false);
            create(activityContent);
        } else {
            throw new TipException("课件文件不存在");
        }
    }

    /**
     * 删除课程内容
     * @param teamId 团队id
     * @param userId 用户di
     * @param activityContentId 课程内容id
     */
    public void deleteActivityContent(Long teamId, Long userId, Long activityContentId) {
        if (!teamService.hasPower(teamId, userId)) {
            throw new TipException("没有权限");
        }
        ActivityContent activityContent = findById(activityContentId);
        if (null != activityContent && !activityContent.getHasDelete()) {
            activityContent.setHasDelete(true);
            activityContent.setUpdateBy(userId);
            activityContent.setUpdateTime(System.currentTimeMillis());
            update(activityContent);
        }
    }

    /**
     * 根据活动查找课件数量
     *
     * @param activityId 活动id
     * @return java.lang.Integer
     */
    public  Integer countActivityContentNumByActivityId(Long activityId) {
        return activityContentMapper.selectCount(new QueryWrapper<ActivityContent>()
                .lambda()
                .eq(ActivityContent::getActivityId, activityId)
                .eq(ActivityContent::getHasDelete, false));
    }

    public ActivityContent findContentByIdAndActivityId(Long activityContentId, Long activityId) {
        return activityContentMapper.selectOne(new QueryWrapper<ActivityContent>()
                .lambda()
                .eq(ActivityContent::getId, activityContentId)
                .eq(ActivityContent::getActivityId, activityId)
                .eq(ActivityContent::getHasDelete, false)
                .orderByDesc(ActivityContent::getCreateTime)
                .last("limit 1"));
    }

}
